package com.ruoyi.web.controller.system;  

import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.CasesNumberProcessadminCus;
import com.ruoyi.system.domain.CasesNumberProcessadminIns;
import com.ruoyi.system.domain.CasesNumberProcessadminRe;
import com.ruoyi.system.service.ICasesNumberProcesscivilService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.CasesNumberProcessadmin;
import com.ruoyi.system.service.ICasesNumberProcessadminService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 行政公益诉讼流程情况Controller
 * 
 * @author ruoyi
 * @date 2025-05-24
 */
@RestController
@RequestMapping("/system/processadmin")
public class CasesNumberProcessadminController extends BaseController
{
    @Autowired
    private ICasesNumberProcessadminService casesNumberProcessadminService;

    @Autowired
    private ICasesNumberProcesscivilService casesNumberProcesscivilService;

    // 定义地区优先级顺序
    private static final List<String> REGION_ORDER = Arrays.asList(
            "本院","哈尔滨市院", "齐齐哈尔市院", "牡丹江市院","佳木斯市院","大庆市院", "鸡西市院", "双鸭山市院","伊春市院",
            "七台河市院", "鹤岗市院",   "黑河市院","绥化市院", "大兴安岭分院", "农垦分院","林区分院","哈尔滨铁路分院", "黑龙江省院"
    );


    /**
     * 查询行政公益诉讼流程情况列表
     */
    @PreAuthorize("@ss.hasPermi('system:processadmin:list')")
    @GetMapping("/list")
    public TableDataInfo list(CasesNumberProcessadmin casesNumberProcessadmin)
    {
        startPage();
        List<CasesNumberProcessadmin> list = casesNumberProcessadminService.selectCasesNumberProcessadminList(casesNumberProcessadmin);
        return getDataTable(list);
    }
    /**
     * 全省公益诉讼检察立案情况统计表
     */
    @PreAuthorize("@ss.hasPermi('system:processadmin:list')")
    @GetMapping("/listRe")
    public TableDataInfo listRe(CasesNumberProcessadmin casesNumberProcessadmin) throws Exception {
        startPage();
        checkDate(casesNumberProcessadmin);
        List<CasesNumberProcessadminRe> list = casesNumberProcessadminService.selectCasesNumberRe(casesNumberProcessadmin);
        List<CasesNumberProcessadminRe> listcivi = casesNumberProcesscivilService.selectCasesNumberRe(casesNumberProcessadmin);
        // Long total=0L;
        //Long totalLast=0L;
        long i=1;
        for (CasesNumberProcessadminRe re : list) {
            for (CasesNumberProcessadminRe recivi : listcivi)
                if (StringUtils.isNotEmpty(re.getDepartmentName()) && re.getDepartmentName().equals(recivi.getDepartmentName())) {
                    re.setCasemxTotal(recivi.getCasemxTotal());
                    re.setCasefmTotal(recivi.getCasefmTotal());
                    Long total = re.getCaseadTotal() + re.getCasefmTotal() + re.getCasemxTotal();
                    Long totalLast = re.getCaseadTotalLast() + recivi.getCasefmTotalLast() + recivi.getCasemxTotal();
                    re.setCaseTotal(total);
                    re.setCaseTotalLast(totalLast);
                    re.setPeryear(StringUtils.strPercent(total-totalLast, totalLast));
                    re.setPerzhanad(StringUtils.strPercent(re.getCaseadTotal(), total));
                    re.setPerzhanfm(StringUtils.strPercent(recivi.getCasefmTotal(), total));
                    re.setPerzhanmx(StringUtils.strPercent(recivi.getCasemxTotal(), total));
                    re.setOrNuber(Long.parseLong(String.valueOf(REGION_ORDER.indexOf(re.getDepartmentName())+1)));
                }
        }
        list.sort(Comparator.comparingInt(
                vo -> REGION_ORDER.indexOf(vo.getDepartmentName())
        ));
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:processadmin:list')")
    @GetMapping("/listIns")
    public TableDataInfo listIns(CasesNumberProcessadmin casesNumberProcessadmin) throws Exception {
        startPage();
        checkDate(casesNumberProcessadmin);
        List<CasesNumberProcessadminIns> list = casesNumberProcessadminService.selectCasesNumberIns(casesNumberProcessadmin);
        List<CasesNumberProcessadminIns> listcivi = casesNumberProcesscivilService.selectCasesNumberIns(casesNumberProcessadmin);
        // Long total=0L;
        //Long totalLast=0L;
        long i=1;
        for (CasesNumberProcessadminIns re : list) {
            for (CasesNumberProcessadminIns recivi : listcivi)
                if (StringUtils.isNotEmpty(re.getDepartmentName()) && re.getDepartmentName().equals(recivi.getDepartmentName())) {
                    Long publishTotal = recivi.getPublishTotal() ;
                    Long publishTotalLast = recivi.getPublishTotalLast();
                    Long zfTotal = re.getCasezfTotal() ;
                    Long zfTotalLast = re.getCasezfTotallast();
                    re.setPublishTotal(publishTotal);
                    re.setPublishTotalLast(publishTotalLast);
                    Long total = zfTotal + publishTotal;
                    Long totalLast = zfTotalLast +publishTotalLast;
                    re.setCaseInsTotal(total);
                    re.setInsyear(StringUtils.strPercent(total-totalLast,totalLast));
                    re.setZfyear(StringUtils.strPercent(zfTotal-zfTotalLast, zfTotalLast));
                    re.setZfZhan(StringUtils.strPercent(zfTotal,total));
                    re.setCorreRate(StringUtils.strPercent(re.getCorreTotal(),re.getCorreTotal()+re.getUnassertTotal()+re.getUncorreTotal()));
                    re.setPublishyear(StringUtils.strPercent(publishTotal-publishTotalLast,publishTotalLast));
                    re.setPublishzhan(StringUtils.strPercent(publishTotal,total));
                    re.setOrNuber(Long.parseLong(String.valueOf(REGION_ORDER.indexOf(re.getDepartmentName())+1)));
                }
        }
        list.sort(Comparator.comparingInt(
                vo -> REGION_ORDER.indexOf(vo.getDepartmentName())
        ));
        return getDataTable(list);
    }

    /**
     * 全省公益诉讼检察磋商情况统计表
     */
    @PreAuthorize("@ss.hasPermi('system:processadmin:list')")
    @GetMapping("/listCus")
    public TableDataInfo listCus(CasesNumberProcessadmin casesNumberProcessadmin) throws Exception {
        startPage();
        checkDate(casesNumberProcessadmin);
        List<CasesNumberProcessadminCus> list = casesNumberProcessadminService.selectCasesNumberCus(casesNumberProcessadmin);
        long i=1;
        for (CasesNumberProcessadminCus re : list) {
            Long cuslast=re.getCaseCusTotallast();
            Long caselast=re.getCaseTotallast();
            re.setPeryear(StringUtils.strPercent(re.getCaseCusTotal()-cuslast, cuslast));
            String perzhan=StringUtils.strPercent(re.getCaseCusTotal(), re.getCaseTotal());
            re.setPerZhan(perzhan);
            String perzhanlast=StringUtils.strPercent(cuslast, caselast);
            BigDecimal num1=new BigDecimal(0.00);
            BigDecimal num2=new BigDecimal(0.00);
            if (perzhan.contains("%")) {
                num1 = new BigDecimal(perzhan.replace("%", ""));
            }
            if (perzhanlast.contains("%")) {
                num2 = new BigDecimal(perzhanlast.replace("%", ""));
            }
            re.setPeryearZhan(num1.subtract(num2)+"%");
            re.setOrNuber(Long.parseLong(String.valueOf(REGION_ORDER.indexOf(re.getDepartmentName())+1)));
        }
        list.sort(Comparator.comparingInt(
                vo -> REGION_ORDER.indexOf(vo.getDepartmentName())
        ));
        return getDataTable(list);
    }

    private static void checkDate(CasesNumberProcessadmin casesNumberProcessadmin) throws Exception {
        Object startTime = casesNumberProcessadmin.getParams().get("beginTime");
        Object endTime = casesNumberProcessadmin.getParams().get("endTime");
        if (null==startTime) {
            throw new Exception("开始时间不能为空");
        } else {
            casesNumberProcessadmin.setStartTime(startTime.toString().substring(0,7));
            casesNumberProcessadmin.setStartTimeLast(StringUtils.strdif(casesNumberProcessadmin.getStartTime()));
        }
        if (null==endTime) {
            throw new Exception("结束时间不能为空");
        } else {
            casesNumberProcessadmin.setEndTime(endTime.toString().substring(0,7) );
            casesNumberProcessadmin.setEndTimeLast(StringUtils.strdif(casesNumberProcessadmin.getEndTime()));
        }
    }


    /**
     * 导出行政公益诉讼流程情况列表
     */
    @PreAuthorize("@ss.hasPermi('system:processadmin:export')")
    @Log(title = "行政公益诉讼流程情况", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CasesNumberProcessadmin casesNumberProcessadmin)
    {
        List<CasesNumberProcessadmin> list = casesNumberProcessadminService.selectCasesNumberProcessadminList(casesNumberProcessadmin);
        ExcelUtil<CasesNumberProcessadmin> util = new ExcelUtil<CasesNumberProcessadmin>(CasesNumberProcessadmin.class);
        util.exportExcel(response, list, "行政公益诉讼流程情况数据");
    }

    /**
     * 导出行政公益诉讼流程情况列表
     */
    @PreAuthorize("@ss.hasPermi('system:processadmin:export')")
    @Log(title = "行政公益诉讼流程情况", businessType = BusinessType.EXPORT)
    @PostMapping("/exportRe")
    public  ResponseEntity<InputStreamResource> exportRe(CasesNumberProcessadmin casesNumberProcessadmin) throws Exception
    {
        // 模拟从数据库查询到的数据
        List<CasesNumberProcessadminRe> dataList = (List<CasesNumberProcessadminRe>) listRe(casesNumberProcessadmin).getRows();
        // 读取模板
        try (InputStream is = new ClassPathResource("附表1.xls").getInputStream();
             Workbook workbook = new HSSFWorkbook(is)) { // 注意：.xls用HSSFWorkbook，.xlsx用XSSFWorkbook
            Sheet sheet = workbook.getSheetAt(0);
            int startRowIndex = 5; // 对应Excel的第7行开始填充数据（因为表头占了前面的行）
            for (int i = 0; i < dataList.size(); i++) {
                CasesNumberProcessadminRe data = dataList.get(i);
                Row row = sheet.getRow(startRowIndex + i) == null ? sheet.createRow(startRowIndex + i) : sheet.getRow(startRowIndex + i);
                // 填充地区列（A列，Java索引0）
                //fillCell(row, 0, data.getRegion());
                // 填充动态数据列（从B列开始，Java索引1）
                fillCell(row, 2, data.getCaseTotal()); // 总计
                fillCell(row, 3, data.getPeryear()); // 同比
                fillCell(row, 4, data.getCaseadTotal()); // 行政数量
                fillCell(row, 5, data.getPerzhanad()); // 行政占比
                fillCell(row, 6, data.getCasemxTotal()); // 刑附民数量
                fillCell(row, 7, data.getPerzhanmx()); // 刑附民占比
                fillCell(row, 8, data.getCasefmTotal()); // 其他民事数量
                fillCell(row, 9, data.getPerzhanfm()); // 其他民事占比
            }
            // 写入到字节数组输出流中
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            // 准备响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=processadminRehaha.xls");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 返回响应实体
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new InputStreamResource(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())));
        }
    }

    @Log(title = "全省公益诉讼检察磋商情况统计表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportCus")
    public  ResponseEntity<InputStreamResource> exportCus(CasesNumberProcessadmin casesNumberProcessadmin) throws Exception
    {
        // 模拟从数据库查询到的数据
        List<CasesNumberProcessadminCus> dataList = (List<CasesNumberProcessadminCus>) listCus(casesNumberProcessadmin).getRows();
        // 读取模板
        try (InputStream is = new ClassPathResource("附表3.xls").getInputStream();
             Workbook workbook = new HSSFWorkbook(is)) { // 注意：.xls用HSSFWorkbook，.xlsx用XSSFWorkbook
            Sheet sheet = workbook.getSheetAt(0);
            int startRowIndex = 4; // 对应Excel的第6行开始填充数据（因为表头占了前面的行）
            for (int i = 0; i < dataList.size(); i++) {
                CasesNumberProcessadminCus data = dataList.get(i);
                Row row = sheet.getRow(startRowIndex + i) == null ? sheet.createRow(startRowIndex + i) : sheet.getRow(startRowIndex + i);
                // 填充动态数据列（从B列开始，Java索引1）
                fillCell(row, 2, data.getCaseCusTotal()); // 磋商案件数量
                fillCell(row, 3, data.getPeryear()); // 同比
                fillCell(row, 4, data.getPerZhan()); // 占比
                fillCell(row, 5, data.getPeryearZhan()); // 占比增减
            }
            // 写入到字节数组输出流中
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            // 准备响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=processadminCushaha.xls");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 返回响应实体
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new InputStreamResource(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())));
        }
    }

    @Log(title = "全省公益诉讼检察磋商情况统计表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportIns")
    public  ResponseEntity<InputStreamResource> exportIns(CasesNumberProcessadmin casesNumberProcessadmin) throws Exception
    {
        // 模拟从数据库查询到的数据
        List<CasesNumberProcessadminIns> dataList = (List<CasesNumberProcessadminIns>) listIns(casesNumberProcessadmin).getRows();
        // 读取模板
        try (InputStream is = new ClassPathResource("附表4.xls").getInputStream();
             Workbook workbook = new HSSFWorkbook(is)) { // 注意：.xls用HSSFWorkbook，.xlsx用XSSFWorkbook
            Sheet sheet = workbook.getSheetAt(0);
            int startRowIndex = 5; // 对应Excel的第6行开始填充数据（因为表头占了前面的行）
            for (int i = 0; i < dataList.size(); i++) {
                CasesNumberProcessadminIns data = dataList.get(i);
                Row row = sheet.getRow(startRowIndex + i) == null ? sheet.createRow(startRowIndex + i) : sheet.getRow(startRowIndex + i);
                // 填充动态数据列（从B列开始，Java索引1）
                fillCell(row, 2, data.getCaseInsTotal()); // 磋商案件数量
                fillCell(row, 3, data.getInsyear()); // 同比
                fillCell(row, 4, data.getCasezfTotal()); // 占比
                fillCell(row, 5, data.getZfyear()); // 占比增减
                fillCell(row, 6, data.getZfZhan()); // 占比增减
                fillCell(row, 7, data.getPublishTotal()); // 占比增减
                fillCell(row, 8, data.getUncorreTotal()); // 占比增减
                fillCell(row, 9, data.getUnassertTotal()); // 占比增减
                fillCell(row, 10, data.getCorreRate()); // 占比增减
                fillCell(row, 11, data.getPublishTotal()); // 占比增减
                fillCell(row, 12, data.getPublishyear()); // 占比增减
                fillCell(row, 13, data.getPublishzhan()); // 占比增减
            }
            // 写入到字节数组输出流中
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            // 准备响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=processinspectRehaha.xls");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 返回响应实体
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new InputStreamResource(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())));
        }
    }
    // 辅助方法：填充单元格
    private void fillCell(Row row, int cellIndex, Object value) {
        Cell cell = row.getCell(cellIndex) == null ? row.createCell(cellIndex) : row.getCell(cellIndex);
        if (value instanceof String) {
            cell.setCellValue((String) value);
        } else if (value instanceof Number) {
            cell.setCellValue(((Number) value).doubleValue());
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        }
        // 可以根据需要添加对其他类型的支持，如日期等
    }
    /**
     * 获取行政公益诉讼流程情况详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:processadmin:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(casesNumberProcessadminService.selectCasesNumberProcessadminById(id));
    }

    /**
     * 新增行政公益诉讼流程情况
     */
    @PreAuthorize("@ss.hasPermi('system:processadmin:add')")
    @Log(title = "行政公益诉讼流程情况", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CasesNumberProcessadmin casesNumberProcessadmin)
    {
        return toAjax(casesNumberProcessadminService.insertCasesNumberProcessadmin(casesNumberProcessadmin));
    }

    /**
     * 修改行政公益诉讼流程情况
     */
    @PreAuthorize("@ss.hasPermi('system:processadmin:edit')")
    @Log(title = "行政公益诉讼流程情况", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CasesNumberProcessadmin casesNumberProcessadmin)
    {
        return toAjax(casesNumberProcessadminService.updateCasesNumberProcessadmin(casesNumberProcessadmin));
    }

    /**
     * 删除行政公益诉讼流程情况
     */
    @PreAuthorize("@ss.hasPermi('system:processadmin:remove')")
    @Log(title = "行政公益诉讼流程情况", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(casesNumberProcessadminService.deleteCasesNumberProcessadminByIds(ids));
    }
}
